<!-- 我发起的康复救助 -->
<template>
  <el-card>
    <el-row>
      <el-form ref="form" :model="searchDto" inline label-width="auto" label-suffix=":">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="searchDto.keywords"
            placeholder="请输入关键字"
            style="width:250px"
          ></el-input>
        </el-form-item>

        <el-form-item label="时间" label-width="60px">
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy年MM月dd日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-s-open" type="primary" @click="clear">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-circle-plus" type="success" @click="handleInitiate">发起申请</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <page-table
      ref="recovery"
      :page-data="pageData"
      :loading="loading"
      :do-get-page-data="getPageData"
    >
      <el-table-column type="index" label="编号" width="80" align="center" />
      <el-table-column prop="recoveryName" label="儿童姓名" align="center" />
      <el-table-column prop="recoveryAge" label="儿童年龄" align="center" />
      <el-table-column prop="recoveryCard" label="身份证号" align="center" />
      <el-table-column prop="applyUserName" label="救助机构" align="center" />
      <el-table-column prop="guardianName" label="监护人" align="center" />
      <el-table-column prop="guardianPhone" label="监护人联系方式" align="center" />
      <el-table-column prop="recoveryTypeName" label="救助类型" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <sz-badge
            :value="scope.row.status | keyText('etkfjzzt')"
            :type="statusStyle(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="开始时间" align="center">
        <template slot-scope="scope">
          {{scope.row.createTime | formatTime("yyyy-MM-dd") }}
        </template>
      </el-table-column>
      <el-table-column prop="recoveryEndTime" label="结束时间" align="center">
        <template slot-scope="scope">
          {{scope.row.recoveryEndTime | formatTime("yyyy-MM-dd") }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-tooltip content="详情" placement="top">
            <el-button
              type="button"
              size="mini"
              icon="el-icon-view"
              @click="viewRecoveryDetail(scope.row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="重新发起" placement="top" v-if="scope.row.status==='CL_REJECT'">
            <el-button
              type="button"
              size="mini"
              icon="el-icon-refresh-right"
              @click="viewDetail(scope.row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="机构确认" placement="top" v-if="scope.row.status==='INSTITUTE_APPLY'">
            <el-button
              type="button"
              size="mini"
              icon="el-icon-s-promotion"
              @click="handleConfirm(scope.row)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </page-table>
    <el-dialog
      :visible.sync="showInitiateDialog"
      v-if="showInitiateDialog"
      title="发起康复救助申请:"
      width="700px"
      @close="fail"
    >
      <el-form
        ref="form"
        :model="formInfo"
        :rules="rules"
        :gutter="10"
        label-width="110px"
        label-suffix="："
        style="padding-right: 20px"
      >
        <el-form-item label="机构名称">
          <el-input placeholder="请输入栏目名称" :value="currentTokenUser.user.name" disabled />
        </el-form-item>
        <el-form-item label="儿童姓名" prop="recoveryName">
          <el-input v-model="formInfo.recoveryName" placeholder="儿童姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="recoveryCard">
          <el-input v-model="formInfo.recoveryCard" placeholder="儿童身份证号" />
        </el-form-item>
        <el-form-item label="年龄" prop="recoveryAge">
          <el-input-number v-model="formInfo.recoveryAge" placeholder="儿童年龄" />
        </el-form-item>
        <el-form-item label="救助类型" prop="recoveryType">
          <el-radio-group v-model="formInfo.recoveryType">
            <div class="radio">
              <div class="radio-label">手术:</div>
              <el-radio
                v-for="item in getDictionary('etkfjzlx-ss')"
                :key="item.keyword"
                :label="item.keyword"
                @change="(e)=>changeRadio(e,'etkfjzlx-ss')"
              >{{item.label}}
              </el-radio>
            </div>
            <div class="radio">
              <div class="radio-label">辅助器具:</div>
              <el-radio
                v-for="item in getDictionary('etkfjzlx-fzqj')"
                :key="item.keyword"
                :label="item.keyword"
                @change="(e)=>changeRadio(e,'etkfjzlx-fzqj')"
              >{{item.label}}
              </el-radio>
            </div>
            <div class="radio">
              <div class="radio-label">康复训练:</div>
              <el-radio
                v-for="item in getDictionary('etkfjzlx-kfxl')"
                :key="item.keyword"
                :label="item.keyword"
                @change="(e)=>changeRadio(e,'etkfjzlx-kfxl')"
              >{{item.label}}
              </el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="康复截止时间" prop="recoveryEndTime">
          <el-date-picker v-model="recoveryEndTime" type="date" disabled />
        </el-form-item>
        <el-form-item label="监护人姓名" prop="guardianName">
          <el-input v-model="formInfo.guardianName" placeholder="监护人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="guardianPhone">
          <el-input v-model="formInfo.guardianPhone" placeholder="监护人联系电话" />
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="formInfo.address" type="textarea" placeholder="家庭住址" />
        </el-form-item>
        <div v-for="(item,index) in formInfo.files" :key="index">
          <el-form-item
            :label="item.label"
            :prop="'files.' + index + '.value'"
            :rules="filesRules.value"
          >
            <picture-upload
              style="margin-left:10px"
              v-model="item.value"
              :type="index"
              path="recovery"
              @del-picture="delPicture"
              @add-picture="addPicture"
            />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClick" :loading="btnLoading">保存</el-button>
        <el-button @click="fail">取消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
import tool from "@/libs/tool";

export default {
  name: 'RecoveryMine',
  data() {
    let validPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      setTimeout(() => {
        if (!tool.isValidPhone(value)) {
          callback(new Error("请输入正确手机号码"));
        } else {
          callback();
        }
      }, 100);
    };

    return {
      date: [],
      btnLoading: false,
      pageData: {},
      loading: false,
      showInitiateDialog: false,
      searchDto: {
        keywords: null,
      },
      recoveryEndTime: null,
      formInfo: {
        recoveryName: null,
        recoveryCard: null,
        recoveryAge: 0,
        recoveryType: null,
        recoveryTypeName: null,
        guardianName: null,
        guardianPhone: null,
        address: null,
        files: [
          { label: '备案表（加章）', value: null },
          { label: '诊断证明', value: null },
          { label: '协议书（加章）', value: null },
          { label: '户主与华子户口本', value: null },
          { label: '监护人身份证或户口', value: null },
          { label: '照片（儿童）', value: null }
        ]
      },
      rules: {
        recoveryName: [{ required: true, message: "请输入儿童姓名", trigger: "blur" }],
        recoveryCard: [{ required: true, validator: this.validCard, trigger: "blur" }],
        recoveryAge: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        recoveryType: [{ required: true, message: "请选择救助类型", trigger: "blur" }],
        guardianName: [{ required: true, message: "请输入监护人姓名", trigger: "blur" }],
        guardianPhone: [{ required: true, trigger: "blur", validator: validPhone }],
      },
      filesRules: {
        value: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
      },
      currentTokenUser: JSON.parse(window.sessionStorage.getItem("userInfo")),
    }
  },
  methods: {
    changeRadio(e, key) {
      const dict = this.getDictionary(key)
      this.formInfo.recoveryTypeName = dict.find(item => item.keyword === e).label
    },
    statusStyle(row) {
      switch (row.status) {
        case "CL_APPLY":
        case "INSTITUTE_APPLY":
          return "warning";
        case "CL_REJECT":
          return "danger";
        case "FINISH":
        case "EVALUATE":
          return "success";
      }
    },
    validCard(rule, value, callback) {
      if (!value) {
        return callback(new Error("请输入身份证号"));
      }
      setTimeout(() => {
        if (!tool.isValidCard(value)) {
          callback(new Error("请输入正确身份证号"));
        } else {
          this.go(value.length);
          callback();
        }
      }, 100);
    },
    go(val) {
      let iden = this.formInfo.recoveryCard;
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let age = 0;

      if (val === 18) {
        age = myDate.getFullYear() - iden.substring(6, 10) - 1;
        if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;

      }
      if (val === 15) {
        age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
        if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
      }

      this.formInfo.recoveryAge = age > 0 ? age : 0
    },
    delPicture(type) {
      this.formInfo.files[type].value = null
    },
    addPicture(val, type) {
      this.formInfo.files[type].value = val
    },
    handleClick() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.btnLoading = true
          const { files, ...para } = this.formInfo
          const filePara = files.map(item => item.value)
          const params = Object.assign(para, { files: filePara.join(','), status: 'CL_APPLY' },)
          this.API.addOrUpdateRecovery({ body: params }).then(res => {
            this.success('发送成功')
            this.getPageData()
            this.fail()
          }).finally(() => {
            this.btnLoading = false
          })
        }
      });
    },
    handleInitiate() {
      this.showInitiateDialog = true
      this.getLastDayOfYear()
    },

    getLastDayOfYear() {
      let year = new Date().getFullYear()
      this.recoveryEndTime = new Date(year + 1, 0, 0)
    },

    fail() {
      this.formInfo = {
        recoveryName: null,
        recoveryCard: null,
        recoveryAge: 0,
        recoveryType: null,
        recoveryTypeName: null,
        guardianName: null,
        guardianPhone: null,
        address: null,
        files: [
          { label: '备案表（加章）', value: null },
          { label: '诊断证明', value: null },
          { label: '协议书（加章）', value: null },
          { label: '户主与华子户口本', value: null },
          { label: '监护人身份证或户口', value: null },
          { label: '照片（儿童）', value: null }
        ]
      }
      this.showInitiateDialog = false

    },
    // 获取分页数据
    getPageData(val) {
      let tem = Object.assign(this.searchDto, val);
      if (this.date) {
        tem.startTime = this.date[0];
        tem.endTime = this.date[1];
      }
      this.API.getInstituteRecoveryPageList(tem).then(ret => {
        this.pageData = ret.data;
      });
    },
    // 查询
    search() {
      this.getPageData();
    },
    //清空
    clear() {
      this.$refs.form.resetFields()
      this.date = [];
      this.getPageData();
    },
    handleConfirm(row) {
      this.$confirm("确定进行机构确认操作吗？", "提示", {}).then(() => {
        const body = Object.assign(JSON.parse(JSON.stringify(row)), { status: 'FINISH' })
        this.API.addOrUpdateRecovery({ body }).then(res => {
          this.success('审核成功');
          this.getPageData()
        }).catch(err => {
          this.error(err)
        })
      }).catch(() => {
      })
    },
    viewDetail(row) {
      this.formInfo = JSON.parse(JSON.stringify(row))
      const fileArr = row.files.split(',')
      this.formInfo.files = [
        { label: '备案表（加章）', value: fileArr[0] },
        { label: '诊断证明', value: fileArr[1] },
        { label: '协议书（加章）', value: fileArr[2] },
        { label: '户主与华子户口本', value: fileArr[3] },
        { label: '监护人身份证或户口', value: fileArr[4] },
        { label: '照片（儿童）', value: fileArr[5] }
      ]
      this.showInitiateDialog = true
    },
    viewRecoveryDetail({ id }) {
      this.$router.push({ name: "recoveryDetail", query: { id } })
    }
  },
  mounted() {
    this.getPageData();
  },
}
</script>
<style scoped lang="scss">
  .radio {
    .radio-label {
      height: 16px;
      color: #333333;
      font-size: 13px;
      margin-bottom: 8px;
    }
  }

  .el-radio {
    margin-bottom: 9px;
  }
</style>
